#include "newpaydialog.h"
#include "ui_newpaydialog.h"
#include <QSqlQuery>
#include <QMessageBox>

void NewPayDialog::setBill(int bill) {
    ui->comboBox->setCurrentIndex(bill);
}

NewPayDialog::NewPayDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewPayDialog)
{
    ui->setupUi(this);
    ui->comboBox->clear();
    QSqlQuery q;
    q.prepare("select name, bill_header_id from pig_bill_headers order by last_modified_date desc");
    q.exec();
    while (q.next()) {
        ui->comboBox->addItem(q.value(0).toString(), q.value(1).toInt());
    }
    ui->comboBox_2->clear();
    q.prepare("select name, pay_type_id from pig_pay_types order by last_modified_date desc");
    q.exec();
    while (q.next()) {
        ui->comboBox_2->addItem(q.value(0).toString(), q.value(1).toInt());
    }
    //Set Date;
    ui->dateEdit->setCalendarPopup(true);
    ui->dateEdit->setDate(QDate::currentDate());
}

NewPayDialog::~NewPayDialog()
{
    delete ui;
}

void NewPayDialog::on_buttonBox_accepted()
{
    if (ui->doubleSpinBox->value() == 0) {
        QMessageBox::warning(this, tr("Pig Bills"), tr("Cannot add 0 payment!"));
        return;
    }
    QSqlQuery q;
    q.prepare("insert into pig_bill_pays (bill_header_id,pay_type_id,bill_date,amount,description,last_modified_date) values (:bill_header_id,:pay_type_id,:bill_date,:amount,:description,datetime('now'))");
    q.bindValue(":bill_header_id", ui->comboBox->currentData().toInt());
    q.bindValue(":pay_type_id", ui->comboBox_2->currentData().toInt());
    q.bindValue(":bill_date", ui->dateEdit->date());
    q.bindValue(":amount", ui->doubleSpinBox->value());
    q.bindValue(":description", ui->plainTextEdit->toPlainText());
    q.exec();
    q.prepare("update pig_bill_headers set amount=(amount+:new), last_modified_date=datetime('now') where bill_header_id=:bill_header_id");
    q.bindValue(":bill_header_id", ui->comboBox->currentData().toInt());
    q.bindValue(":new", ui->doubleSpinBox->value());
    q.exec();
}

void NewPayDialog::on_plainTextEdit_textChanged()
{
    if (ui->plainTextEdit->toPlainText().length() > 1024) {
        ui->plainTextEdit->textCursor().deletePreviousChar();
    }
}
